package com.minelx.scriptbuilder.script;

import com.minelx.scriptbuilder.script.attribute.function.Params;
import com.minelx.scriptbuilder.script.attribute.value.IAttribute;

import java.io.PrintStream;
import java.util.Collections;
import java.util.List;

import static java.util.stream.Collectors.toList;

public class ScriptContext implements IAttribute {

	private final PrintStream out;

	private final VariableManager variableManager;

	public ScriptContext(PrintStream out) {
		this.out = out;
		variableManager = new VariableManager();
	}

	@Override
	public void set(String name, IAttribute value) {
		variableManager.variable(name, value);
	}

	@Override
	public IVariable get(String name) {
		return variableManager.readVariable(name);
	}

	public void pushFunctionFrame(List<String> names, Params realParams) {
		variableManager.pushFrame(names, realParams.values().stream()
				.map(IVariable::value)
				.collect(toList()));
	}

	public void pushFunctionFrame() {
		pushFunctionFrame(Collections.emptyList(), Params.empty());
	}

	public FunctionFrame popFunctionFrame() {
		return variableManager.popFrame();
	}

	public FunctionFrame functionFrame() {
		return variableManager.currentFrame();
	}

	public PrintStream getOutputStream() {
		return out;
	}

	public IVariable variable(String name) {
		return variableManager.variable(name);
	}

	@Override
	public String asString() {
		return "context";
	}
}
